<template>
  <div
  style="height:90%;"
  v-loading="loading"
  element-loading-text="拼命加载中"
  >
  <el-dialog
    title="信息"
    :visible.sync="dialogVisible"
    width="50%"
    :before-close="handleClose">
    <span>阶段材料下载表</span>
    <el-button
    style="margin-left: 40px;"
    type="primary"
    size="mini"
    >全部下载</el-button>
    <el-button
    type="success"
    size="mini"
    >批量下载</el-button>
    <el-divider></el-divider>
    <el-table
        ref="fileMultipleTable"
        @selection-change="handleSelectionChangeFile"
        v-loading="fileLoading"
        element-loading-text="拼命加载中"
        height="300px"
        :data="fileTable"
        :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        style="width: 100%"
        max-height="250">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="filename"
          label="文件名"
          >
        </el-table-column>
        <el-table-column
          prop="filesize"
          label="文件大小"
          >
        </el-table-column>
        <el-table-column
          label="下载链接"
          >
          <template slot-scope="scope">
            <el-button
              @click="downloadMaterial(scope.row.pfPath,scope.row.filename)"
              type="text"
              size="small">
              点击下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  </el-dialog>
    <el-select v-model="selectedBtId" placeholder="请选择所属批次">
        <el-option
          v-for="item in batchOptions"
          :key="item.batchId"
          :label="item.batchName"
          :value="item.batchId">
        </el-option>
      </el-select>

     <el-row style="margin-top: 20px;">
       <el-col :span="12">
          <el-button
          type="primary"
          @click="lotSizeProAudit(10,0)"
          >
            批量通过
          </el-button>
          <el-button
          @click="lotSizeProAudit(11,0)"
          >
            批量不通过
          </el-button>
          <el-button
         @click="lotSizeProAudit(8,0)"
          type="danger"
          >
            批量撤销
          </el-button>
       </el-col>
       <el-col :span="12">
          <p style="text-align: right;margin: 0;">
            <el-button
            type="success"
            @click="auditSubmit"
            >
              审核提交
            </el-button>
          </p>
       </el-col>
     </el-row>

      <el-table
         :row-key="getRowKeys"
         :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
         :cell-style="{'text-align':'center'}"
         ref="multipleTable"
         :data="showTable"
         tooltip-effect="dark"
         style="width: 100%;margin-top:10px;"
         border
         height=85%
         v-loading="tableLoading"
         element-loading-text="数据加载中"
         @selection-change="handleSelectionChange">
         <el-table-column
           type="selection"
           :reserve-selection="true"
           width="55">
         </el-table-column>
         <el-table-column
           prop="proName"
           label="项目名称">
         </el-table-column>
         <el-table-column
           prop="memberName"
           label="主持人">
         </el-table-column>
         <el-table-column
           prop="proDepartment"
           label="项目所属部门">
         </el-table-column>
         <el-table-column
           prop="memberDep"
           label="主持人所属部门"
           show-overflow-tooltip>
         </el-table-column>
         <el-table-column
           width="400px"
           label="操作">
           <template slot-scope="scope">
             <el-button size="mini" @click="checkDetail(scope.row.proId)">查看详情</el-button>
             <el-button size="mini" type="warning" @click="openDialog(scope.row.proId)">下载附件</el-button>
             <el-button
             size="mini"
             type="primary"
             @click="projectAudit(scope.row.proId,10)"
             v-if="scope.row.proApproval!=10 && scope.row.proApproval!=11" >通过</el-button>
             <el-button
             size="mini"
             type="danger"
             @click="projectAudit(scope.row.proId,11)"
             v-if="scope.row.proApproval!=10 && scope.row.proApproval!=11">不通过</el-button>
             <el-button
             size="mini"
             type="danger"
             @click="projectAudit(scope.row.proId,8)"
             v-if="scope.row.proApproval==10">撤销通过</el-button>
             <el-button
             size="mini"
             type="danger"
             @click="projectAudit(scope.row.proId,8)"
             v-if="scope.row.proApproval==11">撤销不通过</el-button>
           </template>
         </el-table-column>
       </el-table>
       <div class="resource-page">
         <el-pagination
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           :page-sizes="[5,10, 15]"
           :page-size="pagesize"
           :pager-count="7"
           layout=" prev, pager, next,sizes, jumper"
           :total="tableData.length"
         >
         </el-pagination>
       </div>
  </div>
</template>

<script>
  import axios from 'axios'
   export default {
     created() {
        this.phaseId=this.$route.query.phaseId
        this.getBatchSelect()
     },
     computed:{
       showTable() {
         return this.tableData.slice(
           (this.currentPage - 1) * this.pagesize,
           this.currentPage * this.pagesize
         );
       },
     },
     watch:{
       selectedBtId(){
         this.showTableByBatchId()
       }
     },
      data() {
        return {
          dialogVisible: false,
          fileLoading:true,
          tableLoading:true,
          loading:true,
          batchName:'',
          phaseId:"",
          pagesize: 5,
          currentPage: 1,
          batchOptions: [],
          selectedBtId: '',
          tableData: [],
          multipleSelection: [],
          multipleSelectionFile: [],
          tempProId:'',
          fileTable:[],
          Base_Api:process.env.Base_API,
          allProjectData:[]
        }
      },
   methods: {
     insertDepRelation(){
       this.$api.department.addDepartmentPhase({
         batchId:this.phaseId,
         depId:this.$store.state.info.bmbh,
         status:1
       }).then((res)=>{
         console.log(res)
       })
     },
     //材料下载
     downloadMaterial(url,fileSort){
      axios.get(this.Base_Api+'/file/fileDownload', {
          headers: {
            token: this.$store.state.token,
            tokenHead: this.$store.state.tokenHead,
            jsession_id: this.$store.state.jsession_id
            },
            responseType: 'blob',
          params: {
           fileName:'test',
           fileUrl:url
          }
      }) .then((res)=>{
        console.log(res)
          //获取最后一个.的位置
          var index= fileSort.lastIndexOf(".");
          //获取后缀
          var ext = fileSort.substr(index+1);
          console.log(ext)
          //rar是用不了，暂且统一使用.zip下载
          var  blog = new Blob([res.data],{type:'application/x-zip-compressed'})
          var  url = window.URL.createObjectURL(blog)
          var  a   = document.createElement('a')
          a.setAttribute('download',fileSort)
          a.setAttribute('href',url)
          a.click()
      }) .catch(function (error) { console.log(error); });
     },
     openDialog(proId){
       console.log(proId)
       this.dialogVisible=true
       this.fileLoading=true
       this.$api.phase.getPhaseFileByProId({proId:proId}).then((res)=>{
         this.fileTable=res.data.data
         this.fileLoading=false
       })
     },
     handleClose(done) {
       this.$confirm('确认关闭？')
         .then(_ => {
           done();
         })
         .catch(_ => {});
      },
     //查看详情
     checkDetail(proId){
        this.$router.push({path:'/checkPdf',query:{pro_id:proId}})
     },
     async auditSubmit(){
       await this.validateIsFullAudit()
       for(let i = 0 ;i<this.allProjectData.length;i++){
         if(this.allProjectData[i].proApproval== 8){
             this.$message({
             	message: "尚有项目未作出选择!",
             	type: "error",
             	offset: screen.height / 2 - 100,
             	center: true,
              duration:2000
             })
             return
         }
       }
       this.$store.commit("getTodoList")
       this.$api.batch.updateBatchStatus({batchId:this.phaseId,status:6}).then((res)=>{
         this.insertDepRelation()
         console.log(res)
         this.$message({
         	message: "提交成功!",
         	type: "success",
         	offset: screen.height / 2 - 100,
         	center: true,
          duration:2000
         })
         this.$router.push({path:'/depPhase'})
       })
     },
     lotSizeProAudit(proApproval,proStatus){
       if(proApproval==10 || proApproval==11){
         let statu
         for(let i = 0;i < this.multipleSelection.length;i++){
           if(proApproval==this.multipleSelection[i].proApproval || this.multipleSelection[i].proApproval==10 || this.multipleSelection[i].proApproval==11){
              statu=true
           }
         }
         if(statu){
           this.$message({
           	message: "请勿选择已操作项目!",
           	type: "warning",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
           return
         }

       }

      if(proApproval==8 ){
        let statu
        for(let i = 0 ; i < this.multipleSelection.length ; i++){
          if(this.multipleSelection[0].proApproval==8){
            statu=true
          }
        }
        if(statu){
          this.$message({
          	message: "请勿选择未操作项目!",
          	type: "warning",
          	offset: screen.height / 2 - 100,
          	center: true,
           duration:2000
          })
          return
        }
      }
       var itemProjectStatu,projectStatus=[]
       itemProjectStatu={proId:'',proApproval:'',proStatus:''}
       this.multipleSelection.forEach(item=>{
          itemProjectStatu.proId=item.proId
          itemProjectStatu.proApproval=proApproval
          itemProjectStatu.proStatus=0
          projectStatus.push(JSON.parse(JSON.stringify(itemProjectStatu)))
       })
       this.$api.project.updateProsByProId({projectStatus:JSON.stringify(projectStatus)}).then((res)=>{
         console.log(res)
         this.showTableByBatchId()
         this.$refs.multipleTable.clearSelection();
         if(proApproval==10){
           this.$message({
           	message: "批量通过操作成功!",
           	type: "success",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
           return
         }
         if(proApproval==11){
           this.$message({
           	message: "批量不通过操作成功!",
           	type: "success",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
           return
         }
         if(proApproval==8){
           this.$message({
           	message: "批量撤销操作成功!",
           	type: "success",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
           return
         }
       })
     },
     getRowKeys(row) {
     				return row.proId;
     			},
     projectAudit(proId,status){
       console.log(proId)
       this.$api.project.updateProByProId({
         proId:proId,
         proApproval:status,
         proStatus:0,
       }).then((res)=>{
         console.log(res)
         this.showTableByBatchId()
         if(status==8){
           this.$message({
           	message: "撤销操作成功!",
           	type: "success",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
         }
         if(status==10){
           this.$message({
           	message: "通过操作成功!",
           	type: "success",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
         }
         if(status==11){
           this.$message({
           	message: "不通过通过操作成功!",
           	type: "success",
           	offset: screen.height / 2 - 100,
           	center: true,
            duration:2000
           })
         }
       })
     },
     //验证此页面所有数据是否已经审批
       validateIsFullAudit(){
        return  this.$api.phase.getSimplifyProjectByPhaseId({phaseId:this.phaseId}).then((res)=>{
        this.allProjectData=res.data.data.filter(item=>item.proDepartment==this.$store.state.info.bm)
      })
     },
     //填充批次选择框
      getBatchSelect(){
        this.$api.phase.getBatchNameByPhaseId({phaseId:this.phaseId}).then((res)=>{
          console.log(res)
          this.batchOptions=res.data.data.batchNames
          //默认选中第一个
          this.selectedBtId=res.data.data.batchNames[0].batchId
        })
      },
      //根据选择框，显示表格
      showTableByBatchId(){
        this.tableLoading=true
        this.$api.phase.getSimplifyProjectByBatchId({batch_id:this.selectedBtId,pro_approvals:'[8,10,11]'}).then((res)=>{
          console.log(res)
          this.tableData=res.data.data
          this.loading=false
          this.tableLoading=false
        })
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
          } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChangeFile(val) {
        this.multipleSelectionFile = val;
        console.log(this.multipleSelectionFile)
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        console.log(this.multipleSelection)
      },
      handleSizeChange(psize) {
        this.pagesize = psize;
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
      },
      }
    }
</script>

<style>
</style>
